package com.ttdevs.ttrss;

import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.alibaba.fastjson.JSONObject;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.ttdevs.ttrss.app.AppInit;
import com.ttdevs.ttrss.bean.ArticleCnbeta;
import com.ttdevs.ttrss.db.IDBCnbetaManager;
import com.ttdevs.ttrss.ui.ArticleListAdapter;

public class CnbetaActivity extends Activity implements OnItemClickListener, OnRefreshListener2<ListView> {
	private static final int PAGESIZE = 20;

	private String url = "http://api.cnbeta.com/capi/phone/newslist?page=0&fromArticleId=0&localLatest=0&limit=20";

	private IDBCnbetaManager dbm;
	private RequestQueue queue;

	private PullToRefreshListView mPullRefreshListView;
	private ListView mListView;

	private ArticleListAdapter adapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_cnbeta);

		queue = AppInit.getRequestQueue();
		dbm = AppInit.getDBCnbetaManager();

		mPullRefreshListView = (PullToRefreshListView) findViewById(R.id.pull_refresh_list);
		mPullRefreshListView.setMode(Mode.BOTH);
		mPullRefreshListView.setOnRefreshListener(this);

		mListView = mPullRefreshListView.getRefreshableView();

		mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		mListView.setOnItemClickListener(this);

	}

	@Override
	public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
		StringRequest mRequest = new StringRequest(url, new Response.Listener<String>() {
			@Override
			public void onResponse(String response) {
				List<ArticleCnbeta> articles = JSONObject.parseArray(response, ArticleCnbeta.class);
				dbm.insertArticles(articles);

				mPullRefreshListView.onRefreshComplete();
			}
		}, new Response.ErrorListener() {
			@Override
			public void onErrorResponse(VolleyError error) {
				System.out.println(">>>>>>endnd:" + System.currentTimeMillis());
				mPullRefreshListView.onRefreshComplete();
			}
		});
		queue.add(mRequest);
	}

	@Override
	public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub

	}
}
